<template>
	<view class="list">
		<card-list-item v-if="haveCard && canShow" v-for="(item,index) in cardList" class="item" :goods="item" @flash="flash" @select="select">
		</card-list-item>
		<view v-if="!haveCard" style="font-size: 28rpx;color: #888888;position: absolute;top: 400rpx;right: 300rpx;">
			购物车为空哦</view>
		
	</view>
</template>

<script>
	export default {
		props: {
			inputStr: {
				type: String,
				default () {
					return ""
				}
			}
		},
		name: "cart-list",
		data() {
			return {
				cardList: [],
				haveCard: false,
				canShow:false,
				selectGoodsList:[]
			};
		},
		methods: {
			flash() {
				this.getCart()
			},
			select(data){
				var hasThisItem = false
				var index = 0
				//不存在则添加，存在则删除
				//console.log(data);
				for(index in this.selectGoodsList){
					if(this.selectGoodsList[index].goodsId == data.goodsId){
						hasThisItem = true
					}
				}
				if(!hasThisItem){
					this.$set(this.selectGoodsList,this.selectGoodsList.length,data)
				}else{
					this.selectGoodsList.splice(index,1)
				}
				this.$emit("getSelectList",this.selectGoodsList)
			},
			getCart() {
				var vue = this
				this.cardList = []
				this.canShow = false
				//获取用户购物车
				this.$request("cart/getOne", {
					userId: uni.getStorageSync("user").id
				}, (res) =>{
					if (res.data.data.length == 0) {
						this.haveCard = false
						uni.hideLoading()
						return
					} else {
						this.haveCard = true
						var allCart = res.data.data
						var userCartGoods=[]
						for(var i in allCart){
							userCartGoods[i] = allCart[i].goodsId
						}
						userCartGoods.sort()
						//删除数组中重复的商品并把它们聚合在一起作为购物车的卡片项
						var now = 0,cur = 1,count = 1,index = 0,countList=[],idList=[];
						while(now <= userCartGoods.length && cur <= userCartGoods.length){
							if(userCartGoods[now] == userCartGoods[cur]){
								//发现重复项目时，将后一个重复项目删除，并使count++
								count++
								cur++
							}else{
								idList[index] = userCartGoods[now]
								countList[index++] = count
								now = cur
								cur++
								count = 1
							}
						}
						//查询全部商品
						this.$request("goods/getAll",{},(res)=>{
							var allGoods = res.data.data
							for(var j in idList){
								var temp = {count:countList[j],goods:{}}
								for(var i in allGoods){
									if(idList[j] == allGoods[i].id){
										temp.goods = allGoods[i]
									}
								}
								this.$set(this.cardList,j,temp)
							}
							uni.hideLoading()
							this.canShow = true
						})
					}
				})
			}
		},
		created() {
			uni.showLoading({})
			this.getCart()
		}
	}
</script>

<style lang="scss">
	.list {
		position: relative;
		height: 1334rpx;
		//border: 2rpx solid blue;
		.item {}
	
	}
</style>
